<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
####################
######php文件上传#####
####################
 class Uploadfile
 {
	private $upfilename;//上传文件的临时
	private $upfiletype; //上传文件的类型
	private $upfileerror; //上传文件的错误类型
	private $upfilesize; //上传文件的大小
	private $mixsize;//最大可上传文件 大小
	private $filename; //移动保存后的文件名
	private $path;//文件的保存路径
	private $filenameurl; //移动保存后的文件路径
	private $filetypes;//允许上传的文件类型
	private $fileurltime;//按时间命名的文件夹目录
	private $pathtime; //是否根据时间生成子目录
	private $upfiletmpname;
	private $extension;//文件扩展名
	private $show;
	private $cover;// 是否使用随机文加名
	private $zroot;//是否使用子目录
    private $upfile_path;//完整的保存路径
	public function __construct($flash = array('jpg','jpeg','png','gif','bmp','flv','mp4'))
	{
		//$uptypes['file'] =array('image/jpg','image/jpeg','image/png','image/pjpeg','image/gif','image/x-png','image/bmp');已作废 改为只判断文件后缀
		$uptypes['flash'] =$flash;
		$this->setfiletypes($uptypes);
		$this->setmixsize(2097152);
		$this->setfilename();
		$this->setcover(false);
		$this->show = '';
	}
	//获取上传文件时的文件名称
	public function setupfilename($filename)
	{
		$this->upfilename = $filename;
	}
	//获取上传文件时的临时文件
	public function setupfiletmpname($filetepname)
	{
		$this->upfiletmpname = $filetepname;
	}
	//获取上传文件的类型
	public function setupfiletype($upfiletype)
	{
		$this->upfiletype = $upfiletype;
	}
	//获取上传文件的错误类型
	public function setupfileerror($upfileerror)
	{
		$this->upfileerror = $upfileerror;
	}
	//获取上传文件的大小
	public function setupfilesize($upfilesize)
	{
		$this->upfilesize = $upfilesize;
	}
	//设置文件的最大可上传大小
	public function setmixsize($mixsize)
	{
		$this->mixsize = $mixsize;
	}
	//获取上传文件的保存路径
	public function setpath($path)
	{
		$this->path = $path;
	}
	// 获取允许上传的文件类型
	public function setfiletypes($filetypes)
	{
		$this->filetypes = $filetypes;
	}
	//保存的文件名称
	public function setfilename($filename = false)
	{
		$this->filename = $filename;
	}

	public function setcover($cover)
	{
		$this->cover = $cover;
	}
	// 是否根据时间生成子目录
	//接受一个参数 布尔值 pathtime
	public function setpathtime($pathtime)
	{
		if(is_bool($pathtime))
		{
                    $this->pathtime = $pathtime;
		}
		else
		{
                    $this->pathtime = false;
		}
	}

	//生成按时间规则的子目录
	private function pathtime()
	{
		if($this->pathtime)
		{
			return '/'.date("Y").'/'.date("m").'/'.date("d").'/';
		}
		else
		{
			return '/';
		}

	}
	//生成新的文件名
	private function newfilenames($path)
	{
		$this->filename = $this->filename?$this->filename:$this->random_string(11);
		if(!file_exists($path.$this->filename.'.'.$this->extension) || $this->cover == true)
		{
			return $this->filename.'.'.$this->extension;
		}
		else
		{
			$this->newfilenames($path);
		}

	}
	//生成文件扩展名
	private function extension()
	{
		switch($this->upfiletype)
		{
			case 'image/jpg':
				$this->extension = 'jpg';
			break;
			case 'image/jpeg':
				$this->extension = 'jpeg';
			break;
			case 'image/png':
				$this->extension = 'png';
			break;
			case 'image/pjpeg':
				$this->extension = 'jpeg';
			break;
			case 'image/gif':
				$this->extension = 'gif';
			break;
			case 'image/x-png':
				$this->extension = 'png';
			break;
			default:
				$this->extension = $this->extend($this->upfilename);
		}
	}
	//生成新的文件路径
	private function newfileurl($filename = 't')
	{
		$this->fileurltime = $this->pathtime();
		if($this->pathtime){
			if($filename == 't')
			{
				$this->pathtime = $this->set_datetime();
			}
			else
			{
				$this->pathtime = $this->set_date();
			}
		}
		$this->filenameurl = $this->path.$this->fileurltime.$this->pathtime;
		$this->createFolder($this->filenameurl);
		$this->newfilenames($this->filenameurl);
		return $this->filenameurl;
	}
	//按时间生成文件名;
	private function set_datetime()
	{
		$this->datetime = date("YmdHis");
	}

	//按日期生成目录名称;
	private function set_date()
	{
		$this->date = date("Y-m-d");
	}
	//判断上传文件是否合法
	private function upfiletnf()
	{
		if(!in_array($this->extension,$this->filetypes['flash']))
		{
			$this->show('上传的文件类型不合法');
			return false;
		}
		return true;
	}
	//判断上传文件是否有错误
	private function fileerrortnf()
	{
		switch($this->upfileerror)
		{
			case '0':
				return true;
			break;
			case '1':
				$this->show('文件尺寸超过允许的最大尺寸');
				return false;
			break;
			case '2':
				$this->show('文件尺寸超过允许的最大尺寸');
				return false;
			break;
			case '3':
				$this->show('只有部分文件被上传');
				return false;
			break;
			case '4':
				$this->show('没有文件被上传');
				return false;
			break;
		}
		return true;
	}
	//判断上传文件 是否超过限制大小
	/** parm：bool $tnf - 是否限制大小
	** return: bool
	*/
	private function filesizetnf($tnf = false)
	{
		if($tnf ===  false)
		{
			return true;
		}
		if($this->upfilesize > $this->mixsize)
		{
			$this->show('文件超过限制大小');
			return false;
		}
	}

	private function extend($file_name)
	{
            $extend =explode("." , $file_name);
            return end($extend);
	}

	//移动文件
	private function movefile()
	{
                $this->upfile_path = $this->filenameurl.$this->filename.'.'.$this->extension;
		if(move_uploaded_file($this->upfiletmpname,$this->filenameurl.$this->filename.'.'.$this->extension))
		{
			$this->show('文件上传成功');
			return true;
		}
		else
		{
			$this->show('移动文件失败');
			return false;
		}
	}

	//判断目录是否存在
	private function mk_dir()
	{
		if (! file_exists($this->path.$this->fileurltime)){   //检测根目录是否存在;
			@$this->createFolder($this->path.$this->fileurltime);     //不存在则创建;
		}
	}
	//信息提示
	private function show($errstr="未知错误！"){
		$this->show .= $errstr;
	}
	function save()
	{
		if(!$this->fileerrortnf())     //判断上传文件是否有错误
		{
			return false;
		}

		$this->extension();
		if(!$this->upfiletnf()) //判断文件是否合法
		{
			return false;
		}
		if(!$this->filesizetnf()) //判断上传文件是否超过限制大小
		{
			return false;
		}
		$this->mk_dir();        //如果目录不存在则创建;
		$this->newfileurl('t'); //生成新文件名

		return $this->movefile();     //移动文件;
	}
	//返回文件名
	public function upfilename()
	{
		return $this->filename;
	}
	//返回子目录名称
	public function upfilenameurl()
	{
		return $this->filenameurl;
	}
	//返回文件扩扎名
	public function upextension()
	{
		return $this->extension;
	}
	public function upshow()
	{
		return $this->show;
	}

	//是否使用当前目录
	public function getzroot($zroot)
	{
		$this->zroot = $zroot;
	}
        //返回完整的文件路径
        public function getupfile_path()
        {
            return $this->upfile_path;
        }

	//php创建目录函数，支持嵌套创建目录
	public function createFolder($pFolder){
                        if(preg_match ("/win/i", PHP_OS)){
                                     $pFolder=str_replace('/', '\\', $pFolder);
                                     $RootFolder=str_replace('/', '\\', $_SERVER['DOCUMENT_ROOT']);

                                     //判断要生成目录是否为根目录
                                     if(substr($pFolder,0,1) == DIRECTORY_SEPARATOR ) {
                                              $pFolder = $RootFolder.$pFolder;
                                     }
                        }
                        else
                             {
                                     //判断要生成目录是否为根目录
                                     if(substr($pFolder,0,1) != DIRECTORY_SEPARATOR) {
                                              $pFolder = $_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.$pFolder;
                                     }else{
                                             $pFolder = DIRECTORY_SEPARATOR.$pFolder;
                                     }
                        }

                        $folder = explode(DIRECTORY_SEPARATOR,$pFolder);
                        $mkfolder = '';
                        for($i=0; isset($folder[$i]); $i++){
                             $mkfolder .= $folder[$i];
                             if(@!is_dir($mkfolder))
                             @mkdir("$mkfolder", 0777);
                             $mkfolder .= DIRECTORY_SEPARATOR;
        }
     }
     
     		//产生随机字符
	public function random_string($length, $max=FALSE)
	{
		  if (is_int($max) && $max > $length)
		  {
			$length = mt_rand($length, $max);
		  }
		  $output = '';

		  for ($i=0; $i<$length; $i++)
		  {
			$which = mt_rand(0,2);

			if ($which === 0)
			{
			  $output .= mt_rand(0,9);
			}
			elseif ($which === 1)
			{
			  $output .= chr(mt_rand(65,90));
			}
			else
			{
			  $output .= chr(mt_rand(97,122));
			}
		  }
		  return $output;
	}

}